# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

from WebBase import Base

class ItemOperation(Base):

    @view_config(route_name='AppWebItemEditIndexRoute', renderer='../../templates/AppWebItemEdit.pt')
    def AppWebItemEditIndexRoute(self):
        md5, tel, username, email, type, portrait, csc, tString, eString, tokenString = '', '', '', '', '', '', '', '', '', ''
        try:
            tel = self.request.session['tel']
            md5 = self.request.params['md5']
            username = self.request.session['username']
            email = self.request.session['email']
            type = self.request.session['type']
            portrait = self.request.session['portrait'].replace('/media', '/static')
            tString = self.request.session['tString']
            eString = self.request.session['eString']
            tokenString = self.request.session['tokenString']
        except:
            return HTTPFound(location='/')
        tmpTokenString = self.calculateToken(tString, tel)
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '114', 'message': '登录流程验证失败!', 'data': '重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return HTTPFound(location='/')
        sql = "select name, category, size, material, weight, price, aperture, url, description, path from material_info where md5 = %s"
        result = MySqlCRUD.selectImpl(sql, md5)
        size = result[0]['size'].split('*')
        map_size = {'size_x': size[0], 'size_y': size[1], 'size_z': size[2]}
        map = {'tel': tel, 'username': username, 'email': email, 'type': type, 'portrait': portrait, 'md5': md5}
        map.update(result[0])
        map.update(map_size)
        map.pop('size')
        map['path'] = map['path'].replace('/media', '/static')
        log.debug(map)
        return map

    @view_config(route_name='AppWebItemEditRoute', request_method='POST')
    def AppWebItemEditRoute(self):
        postParams =  self.request.POST
        log.debug(postParams)
        md5, category, name, material, size, weight, aperture, price, description, url ='', '', '', '', '', '', '', '', '', ''
        try:
            md5 = postParams.get('md5', '')
            category = postParams.get('category', '')
            name = postParams.get('name', '')
            material = postParams.get('material', '')
            size = postParams.get('size', '')
            weight = postParams.get('weight', '')
            aperture = postParams.get('aperture', '')
            price = postParams.get('price', '')
            description = postParams.get('description', '')
            url = postParams.get('url', '')

            log.debug('[AppWebItemEdit][md5]' + md5)
            log.debug('[AppWebItemEdit][category]' + category)
            log.debug('[AppWebItemEdit][name]' + name)
            log.debug('[AppWebItemEdit][material]' + material)
            log.debug('[AppWebItemEdit][size]' + size)
            log.debug('[AppWebItemEdit][weight]' + weight)
            log.debug('[AppWebItemEdit][aperture]' + aperture)
            log.debug('[AppWebItemEdit][price]' + price)
            log.debug('[AppWebItemEdit][description]' + description)
            log.debug('[AppWebItemEdit][url]' + url)

        except Exception, e:
            log.error(e)
        UploadTasks.updateMaterialInfoByQueue(md5, self.request.session['tel'], category, \
            name, material, size, weight, aperture, price, description, url)
        return Response("上传成功！")

    @view_config(route_name='AppWebItemDeleteRoute', request_method='POST')
    def AppWebItemDeleteRoute(self):
        postParams =  self.request.POST
        log.debug(postParams)
        md5, tel ='', ''
        try:
            md5 = postParams.get('md5', '')
            tel = postParams.get('tel', '')

            log.debug('[AppWebItemEdit][md5]' + md5)
            log.debug('[AppWebItemEdit][tel]' + tel)
        except Exception, e:
            log.error(e)
        UploadTasks.deleteMaterialUserInfoByQueue(md5, tel)
        return Response("上传成功！")

